<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Request;
use Hash;
class User extends Model
{
    /*注册API*/
    public function signup()
    {
        /*检查用户名和密码是否填写*/
        $has_username_and_password = $this->has_username_and_password();
        if (!$this->has_username_and_password())
            return ['status' => 0, 'msg' => '用户名和密码都不可为空'];

        $username = $has_username_and_password[0];
        $password = $has_username_and_password[1];

        /*检查用户是否存在*/
        $user_exists = $this
            ->where('username', $username)
            ->exists();
        if ($user_exists){
            return ['status' => 0, 'msg' => '用户名已存在'];
        }

        /*加密密码*/
        $hashed_password = Hash::make($password);
        //$hashed_password = bcrypt($password);

        /*存入数据库*/
        $user = $this;
        $user->password = $hashed_password;
        $user->username = $username;
        $user->save();
        if ($user->save())
            return ['status' => 1, 'id' => $user->id];
        else
            return ['status' => 0, 'msg' => 'DB insert Failed'];
    }

    /*登陆API*/
    public function login()
    {
        /*检查用户名和密码是否填写*/
        $has_username_and_password = $this->has_username_and_password();
        if (!$has_username_and_password)
        return ['status' => 0, 'msg' => '用户名和密码都不可为空'];

        $username = $has_username_and_password[0];
        $password = $has_username_and_password[1];

        /*检查用户是否存在*/
        $user = $this->where('username', $username)->first();
        if (!$user)
            return ['status' => 0, 'msg' => '用户不存在'];

        /*检查密码是否正确*/
        $hashed_password = $user->password;
        if (!Hash::check($password, $hashed_password))
            return ['status' => '0', 'msg' => '登陆失败'];

        /*将用户信息写入Session*/
        session()->put('username', $user->username);
        session()->put('user_id', $user->id);

        return ['status' => '1', 'msg' => '登陆成功'];
    }

    /*简化注册和登陆时，对用户的账号密码判断是否为空*/
    public function has_username_and_password()
    {
        $username = Request::get('username');
        $password = Request::get('password');

        /*检查用户名和密码是否为空*/
        if ($username && $password)
            return [$username, $password];
        return false;
    }

    /*退出登陆API*/
    public function logout()
    {
        /*应用小可以用flush清空所有session信息*/
        //session()->flush();
        /*如果要跟踪用户退出后的一些信息*/

        session()->forget('username');
        session()->forget('user_id');
        return redirect('/');
        return ['status' => 1];
        //dd(session()->all());
    }


    /*检测用户是否登陆*/
    public function is_logged_in()
    {
        /*如果session中存在user_id则返回user_id;否则返回false*/
        return session('user_id')?:false;
    }

    /* 跨表查询的通用API,Laravel多对多跨表查询神器：中间表Pivot */
    public function answers()
    {
      /* 手动添加的字段需要注册 */
      return $this
      ->belongsToMany('App\Answer')
      ->withPivot('vote')
      ->withTimestamps();
    }


}
